/* Copyright (C) 2003, Charles Wang.
 * Author:  Charles Wang <charles@linux.net.cn>
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANT; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public LIcense for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, 59 Temple
 * Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include  <sys/types.h>
#include  <sys/stat.h>
#include  <errno.h>
#include  <fcntl.h>
#include  <stdarg.h>
#include  <stdio.h>
#include  <string.h>
#include  <unistd.h>
#include  <newt.h>
#include  "mblog.h"

int  mbfd1 = -1, mbfd2 = -1;
char logbuffer[16384], *curlog = logbuffer;

void mblog_open(void) {
    int  en1, en2;
    mbfd1 = open("/dev/tty2", O_WRONLY | O_SYNC);
    if (mbfd1 < 0)  en1 = errno;
    mbfd2 = open("/var/log/magicbooter.log",
		 O_WRONLY | O_CREAT | O_SYNC, 0600);
    if (mbfd2 < 0)  en2 = errno;

    curlog = logbuffer;

    if (mbfd1 < 0)  mblog("open /dev/tty2 failed: %s\n", strerror(en1));
    if (mbfd2 < 0)  mblog("open /var/log/magicbooter failed: %s\n", strerror(en2));
}
void mblog_close(void) {
    if (mbfd1 >= 0)  close(mbfd1);
    if (mbfd2 >= 0)  close(mbfd2);
}

void mblog(const char *fmt, ...) {
    va_list  ap;
    char  logbuf[256];
    int   l;

    va_start(ap, fmt);
    vsnprintf(logbuf, sizeof(logbuf), fmt, ap);
    va_end(ap);
    l = strlen(logbuf);
    if (mbfd1 >= 0)
	write(mbfd1, logbuf, l);
    if (mbfd2 >= 0)
	write(mbfd2, logbuf, l);
    if (!(mbfd1 >= 0 || mbfd2 >= 0))
        fprintf(stderr, logbuf);
    if (curlog - logbuffer + l + 1 > sizeof(logbuffer)) {
	char *src = logbuffer + (curlog - logbuffer + l + 1 - sizeof(logbuffer));
	memmove(logbuffer, src, curlog - src);
	curlog -= src - logbuffer;
    }
    strcpy(curlog, logbuf);
    curlog += l;
}

void show_mblog(void) {
    newtWinMessage("LOG", "Close", logbuffer);
}

